SPORE.$Import('core.core');

/*
---

name: Function

description: Contains Function Prototypes like create, bind, pass, and delay.

license: MIT-style license.

requires: Type

provides: Function

...
*/

SPORE.register('core.function',function($ns){

	Function.extend({
	
		attempt: function(){
			for (var i = 0, l = arguments.length; i < l; i++){
				try {
					return arguments[i]();
				} catch (e){}
			}
			return null;
		}
	
	});
	
	Function.implement({
	
		attempt: function(args, bind){
			try {
				return this.apply(bind, Array.from(args));
			} catch (e){}
			
			return null;
		},
	
		/*<!ES5>*/
		bind: function(bind){
			var self = this,
				args = (arguments.length > 1) ? Array.slice(arguments, 1) : null;
			
			return function(){
				if (!args && !arguments.length) return self.call(bind);
				if (args && arguments.length) return self.apply(bind, args.concat(Array.from(arguments)));
				return self.apply(bind, args || arguments);
			};
		},
		/*</!ES5>*/
	
		pass: function(args, bind){
			var self = this;
			if (args != null) args = Array.from(args);
			return function(){
				return self.apply(bind, args || arguments);
			};
		},
	
		delay: function(delay, bind, args){
			return setTimeout(this.pass((args == null ? [] : args), bind), delay);
		},
	
		periodical: function(periodical, bind, args){
			return setInterval(this.pass((args == null ? [] : args), bind), periodical);
		}
	
	});

});